package simple.word;

import java.io.ByteArrayInputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.util.List;



import org.apache.commons.io.IOUtils;
import org.jdom2.Document;
import org.jdom2.Element;
import org.jdom2.JDOMException;
import org.jdom2.Namespace;
import org.jdom2.filter.Filters;
import org.jdom2.input.SAXBuilder;
import org.jdom2.input.sax.XMLReaderSAX2Factory;
import org.jdom2.output.XMLOutputter;
import org.jdom2.xpath.XPath;
import org.jdom2.xpath.XPathExpression;
import org.jdom2.xpath.XPathFactory;
import org.jdom2.xpath.jaxen.JaxenXPathFactory;
import org.jsoup.Jsoup;
import org.xml.sax.InputSource;

public class Lookup {
	final static String LINK = "http://dict.cn/";
	
	public Lookup() {
	}

	public LookupResult lookup(final String word) throws Exception {

		LookupResult result = new LookupResult();
		
		//result.setWord(word);

		String link = LINK + URLEncoder.encode(word, "utf-8");
		URL url = new URL(link);
		
		HttpURLConnection connection = (HttpURLConnection)url.openConnection();
		connection.setConnectTimeout(3000);
		InputStream is = connection.getInputStream();

		parseContent(is, result, word);
		
		is.close();
		
		return result;
	}

	LookupResult parseContent(InputStream is, LookupResult result, String word) throws JDOMException, IOException {
		XMLReaderSAX2Factory factory = 
				new XMLReaderSAX2Factory(false, "org.ccil.cowan.tagsoup.Parser");
		SAXBuilder saxBuilder = new SAXBuilder(factory);
		InputSource inputSource = new InputSource(is);
		inputSource.setEncoding("utf-8");
		Document doc = saxBuilder.build(inputSource);

		XPathFactory xpathFactory = XPathFactory.instance();
		Namespace namespace = Namespace.getNamespace("xhtml", "http://www.w3.org/1999/xhtml");
		
		//<h1 class="keyword">swing</h1>
		XPathExpression<Element> expWord = 
				xpathFactory.compile("//xhtml:h1[@class='keyword']", Filters.element(), null, namespace);
		List<Element> elmsWord = expWord.evaluate(doc);
		if(elmsWord.isEmpty())
			return result;
		
		result.setWord(elmsWord.get(0).getText());
		
		XPathExpression<Element> exp = 
				xpathFactory.compile("//xhtml:div[@class='layout basic']/xhtml:ul/xhtml:li//node()", Filters.element(), null, namespace);
		List<Element> elms = exp.evaluate(doc);
		StringBuilder stringBuilder = new StringBuilder();
		
		if(elms != null && elms.size() > 0) {
			for(Element elm : elms) {						
				if(elm.getText().length() > 0)
					stringBuilder.append(elm.getText()).append(" ");
			}
		}
		
		result.setExplain(stringBuilder.toString().trim());
		
		return result;
	}

}
